import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_first_station/guess/guess_app_bar.dart';
import 'package:flutter_first_station/storage/sp_storage.dart';

import 'guess_result_notice.dart';

class GuessPage extends StatefulWidget {
  const GuessPage({super.key, required this.title});

  final String title;

  @override
  State<GuessPage> createState() => _GuessPageState();
}

class _GuessPageState extends State<GuessPage>
    with AutomaticKeepAliveClientMixin {
  final Random _random = Random();
  int _value = 0;
  bool _guessing = false; // 是否猜数中
  bool? _isBig; // null: 相等  true: 大了  false: 小了

  // 生成随机数
  void _generateRandomValue() {
    setState(() {
      _guessing = true;
      _value = _random.nextInt(100);
      SpStorage.instance.saveGuess(guessing: _guessing, value: _value); // 保存sp
    });
  }

  // 校验输入的数字
  void _onCheck() {
    int? guessValue = int.tryParse(_guessCtrl.text);
    // 游戏未开始 or 输入非整数
    if (!_guessing || guessValue == null) return;

    // 猜对了
    if (guessValue == _value) {
      setState(() {
        _isBig = null;
        _guessing = false;
      });
      return;
    }

    // 猜错了
    setState(() {
      _isBig = guessValue > _value;
    });
  }

  // 输入控制器
  final TextEditingController _guessCtrl = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: GuessAppBar(
        onCheck: _onCheck,
        controller: _guessCtrl,
      ),
      body: Stack(children: [
        if (_isBig != null)
          Column(
            children: [
              if (_isBig!)
                const ResultNotice(color: Colors.redAccent, info: "大了"),
              const Spacer(),
              if (!_isBig!)
                const ResultNotice(color: Colors.blueAccent, info: "小了"),
            ],
          ),
        Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              if (!_guessing)
                const Text(
                  '点击生成随机数：',
                ),
              Text(
                _guessing ? '**' : '$_value',
                style:
                    const TextStyle(fontSize: 68, fontWeight: FontWeight.bold),
              ),
            ],
          ),
        )
      ]),
      floatingActionButton: FloatingActionButton(
        backgroundColor: _guessing ? Colors.grey : Colors.blue,
        onPressed: _guessing ? null : _generateRandomValue,
        tooltip: 'Increment',
        child: const Icon(Icons.generating_tokens_outlined),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    // 读取 sp 配置
    _initConfig();
  }

  void _initConfig() async {
    Map<String, dynamic> config = await SpStorage.instance.readGuessConfig();
    _guessing = config['guessing'] ?? false;
    _value = config['value'] ?? 0;
    setState(() {});
  }

  @override
  void dispose() {
    _guessCtrl.dispose();
    super.dispose();
  }

  @override
  bool get wantKeepAlive => true;
}
